<?php
/**
 * 营销活动
 *
 * @author maolvxiansheng 2018年9月7日 14点03分
 * @copyright  Copyright (c) 中国追溯
 * @since      File available since Release v1.1
 */
defined('InShopNC') or exit('Access Invalid!');
class marketing_activityModel extends Model {

    const   ACTIVITY_CLOSE         = 0;     //活动关闭标识
    const   ACTIVITY_OPEN          = 1;     //活动开启标识
    const   ACTIVITY_HIDE          = 0;     //活动隐藏标识
    const   ACTIVITY_SHOW          = 1;     //活动显示标识
    const   ACTIVITY_TYPE_NEWBIE   = 1;     //活动类型-新人专场
    const   ACTIVITY_TYPE_SECAKILL = 2;     //活动类型-限时折扣(全商城)
    const   ACTIVITY_TYPE_KANJIA   = 3;     //活动类型-砍价(全商城)
    const   ACTIVITY_TYPE_PINTUAN  = 4;     //活动类型-拼团(全商城)
    const   STORE_GOODS_LIMIT      = 5;     //默认活动单一店铺最多可以报名商品数（0：不限制）
    const   ENCRYPT_SALT           = 'H$GkjhdfJH24DS@F';  //报名链接加密盐

    private $marketing_activity_type;
    private $activity_type_map_relation;

    public function __construct(){
        parent::__construct();
        //营销类型
        $this->marketing_activity_type = array('newbie' => array('sign' => self::ACTIVITY_TYPE_NEWBIE, 'name' => '新人专场'), 'secakill' => array('sign' => self::ACTIVITY_TYPE_SECAKILL, 'name' => '限时折扣(全商城)'), 'kanjia' => array('sign' => self::ACTIVITY_TYPE_KANJIA, 'name' => '砍价(全商城)'), 'pintuan' => array('sign' => self::ACTIVITY_TYPE_PINTUAN, 'name' => '拼团(全商城)'));
        //营销类型对应数据存放关系
        $this->activity_type_map_relation = array(
                                                    self::ACTIVITY_TYPE_NEWBIE => array('table' => 'p_newbie_goods', 'if_promotion' => false),
                                                    self::ACTIVITY_TYPE_SECAKILL => array('table' => 'p_xianshi_all_goods', 'if_promotion' => true),
                                                    self::ACTIVITY_TYPE_KANJIA => array('table' => 'p_kanjia_goods', 'if_promotion' => false),
                                                    self::ACTIVITY_TYPE_PINTUAN => array('table' => 'p_pintuan_goods', 'if_promotion' => false),
                                                );
    }

    /**
     * 得到营销活动类型
     * @return array
     */
    public function getMarketingActivityType()
    {
        return array_column($this->marketing_activity_type, 'name', 'sign');
    }

    /**
     * 生成加密的商铺营销活动报名链接
     * @param  integer $marketing_activity_id 营销活动id
     * @return string
     */
    public function createEncryptStoreActivityApplyLink($marketing_activity_id = 0)
    {
        return SHOP_SITE_URL . DS . 'index.php?act=store_marketing_activity&op=apply_activity_hide&marketing_activity_id=' . encrypt($marketing_activity_id, self::ENCRYPT_SALT);
    }

    /**
     * 解密得到有效活动报名id
     * @param  string $marketing_activity_id 加密的活动id
     * @return string
     */
    public function decryptActivityApplyId($marketing_activity_id = '')
    {
        $marketing_activity_id = decrypt($marketing_activity_id, self::ENCRYPT_SALT);
        return is_numeric($marketing_activity_id) ? (int)$marketing_activity_id : 0;
    }

    /**
     * 获得营销活动列表
     * @param  array   $where        条件
     * @param  string  $order        排序
     * @param  boolean $demand_goods 是否查询商品
     * @param  int     $limit        条数限制
     * @param  int     $member_id    会员id
     * @return array
     */
    public function getMarketingActivityList($where = array(), $order = 'marketing_activity.marketing_activity_sort ASC', $demand_goods = false, $limit = 0, $member_id = 0)
    {
        $result = false;
        $field = 'marketing_activity.marketing_activity_id,marketing_activity.marketing_activity_title,marketing_activity.marketing_activity_type,marketing_activity.marketing_activity_banner,marketing_activity.marketing_activity_style,marketing_activity.marketing_activity_apply_start_date,marketing_activity.marketing_activity_apply_end_date,marketing_activity.marketing_activity_start_date,marketing_activity.marketing_activity_end_date,marketing_activity.store_goods_limit,marketing_activity.marketing_activity_sort,marketing_activity.marketing_activity_state,marketing_activity.marketing_activity_show,marketing_activity_extend.marketing_activity_desc';
        $result = $this->table('marketing_activity,marketing_activity_extend')
                       ->field($field)
                       ->join('left')
                       ->on('marketing_activity.marketing_activity_id = marketing_activity_extend.marketing_activity_id')
                       ->where($where)
                       ->limit((int)$limit)
                       ->select();
        $activity_data = array();   //活动数据
        $activity_type_ids = array(); //存放营销活动各种类型的营销id
        array_walk($result, function(&$item, $keys)use(&$activity_data, &$activity_type_ids){
            //横幅全地址
            $item['marketing_activity_banner_all'] = (isset($item['marketing_activity_banner']) && !empty($item['marketing_activity_banner'])) ? UPLOAD_SITE_URL.DS.ATTACH_ACTIVITY.DS.$item['marketing_activity_banner'] : '';
            $activity_type_ids[$item['marketing_activity_type']][] = $item['marketing_activity_id'];
            $activity_data[$item['marketing_activity_id']] = $item;
        });

        //是否查询下属商品
        if ($demand_goods) {
            foreach ($activity_type_ids as $marketing_activity_type => $marketing_activity_ids) {
                $model_name = $this->activityTypeShiftModel($marketing_activity_type);
                if (!$model_name) continue;

                $model_name = Model($model_name);
                $goods_data = $model_name->getListDataPass($marketing_activity_ids);
                foreach ($goods_data as $item) {
                    $buy_jurisdiction = true;    //是否具有权限
                    //是否存在会员id，若存在检查是否具有权限
                    if ($member_id) {
                        $buy_jurisdiction = $model_name->checkMemberBuyJurisdiction($member_id, $item);
                        $buy_jurisdiction = ($buy_jurisdiction === true) ? false : true;
                    }

                    //商品图片
                    $item['goods_image_url'] = cthumb($item['goods_image'], 360, $item['store_id']);
                    //折扣
                    $item['discount'] = number_format(($item['promotion_price'] / $item['goods_price']), 2, '.', '');
                    if (isset($activity_data[$item['marketing_activity_id']]) && $buy_jurisdiction) $activity_data[$item['marketing_activity_id']]['goods_list'][$item['goods_id']] = $item;
                }
            }
        }
        return $activity_data;
    }

    /**
     * 活动列表
     *
     * @param array $condition 查询条件
     * @param int $page 分页数
     * @return array 二维数组
     */
    public function getList($where, $field = '*', $limit = 0, $page = 0, $order = 'marketing_activity.marketing_activity_id', $if_desc = true)
    {
        $map = $this->getCondition($where);
        if ($if_desc)  {
            $on = 'marketing_activity.marketing_activity_id = marketing_activity_extend.marketing_activity_id';
            $activity_lists = $this->table('marketing_activity,marketing_activity_extend')->field($field)->join('left')->on($on)->limit($limit)->where($map)->limit($page)->order($order)->select();
        } else {
            $activity_lists = $this->table('marketing_activity')->field($field)->limit($limit)->where($map)->limit($page)->order($order)->select();
        }
        //获取活动类型
        $marketing_activity_type = $this->getMarketingActivityType();
        if (!empty($activity_lists) && is_array($activity_lists)) {
            $marketing_activity = $this;
            array_walk($activity_lists, function(&$item, $keys)use($marketing_activity_type, $marketing_activity){
                //活动类型
                if (isset($item['marketing_activity_type'])) {
                    $item['marketing_activity_type_text'] = isset($marketing_activity_type[$item['marketing_activity_type']]) ? $marketing_activity_type[$item['marketing_activity_type']] : 'unknown';
                }
                //活动简介
                $item['marketing_activity_desc_html'] =  isset($item['marketing_activity_desc']) ? $item['marketing_activity_desc'] : '';
                $item['marketing_activity_desc'] =  isset($item['marketing_activity_desc']) ? msubstr(strip_tags(html_entity_decode($item['marketing_activity_desc'])), 0, 60) : '';

                //报名时间
                $item['marketing_activity_apply_date'] = date('Y-m-d H:i', $item['marketing_activity_apply_start_date']) . '<br />' . date('Y-m-d H:i', $item['marketing_activity_apply_end_date']);
                //活动时间
                $item['marketing_activity_date'] = date('Y-m-d H:i', $item['marketing_activity_start_date']) . '<br />' . date('Y-m-d H:i', $item['marketing_activity_end_date']);

                //活动状态
                $apply_state = ($item['marketing_activity_apply_start_date'] < TIMESTAMP && $item['marketing_activity_apply_end_date'] > TIMESTAMP) ? '报名中' : (($item['marketing_activity_apply_end_date'] < TIMESTAMP) ? '报名时间已结束' : '未到报名时间');
                $activity_state = ($item['marketing_activity_start_date'] < TIMESTAMP && $item['marketing_activity_end_date'] > TIMESTAMP) ? '活动进行中' : (($item['marketing_activity_end_date'] < TIMESTAMP) ? '活动已结束' : '活动未开始');
                $item['marketing_activity_state_text'] = $apply_state . '<br />' . $activity_state;

                //商家报名链接
                $item['store_activity_apply'] = $marketing_activity->createEncryptStoreActivityApplyLink($item['marketing_activity_id']);
                //横幅全地址
                $item['marketing_activity_banner_all'] = (isset($item['marketing_activity_banner']) && !empty($item['marketing_activity_banner'])) ? UPLOAD_SITE_URL.DS.ATTACH_ACTIVITY.DS.$item['marketing_activity_banner'] : '';
            });
        }
        return $activity_lists;
    }

    /**
     * 检查商户是否报名该活动
     * @param  int  $store_id 商家id
     * @param  array  $activity_list 需要检查的数据
     * @return array
     */
    public function checkMerchantApply($store_id, $activity_list = array())
    {
        $dispose_data = array();    //处理后的数据
        $activity_type_array = array(); //存储活动类型，及其相应数据
        array_walk($activity_list, function($item, $keys)use(&$dispose_data, &$activity_type_array){
            $dispose_data[$item['marketing_activity_id']] = $item;
            $activity_type_array[$item['marketing_activity_type']]['ids'][] = $item['marketing_activity_id'];
            if (!isset($activity_type_array[$item['marketing_activity_type']]['model'])) {
                $activity_type_array[$item['marketing_activity_type']]['model'] = $this->activityTypeShiftModel($item['marketing_activity_type']);
            }
        });
        unset($activity_list);

        $apply_state_array = array();   //存放检查后的商家报名数据
        //查询相应数据是否存在报名数据
        array_walk($activity_type_array, function($item, $activity_id) use (&$apply_state_array, $store_id){
            if ( !isset($item['model']) || empty($item['model']) ) continue;

            $model = Model($item['model']);
            $apply_state_temporary = $model->getMerchantApplyState($store_id, $item['ids']);
            $apply_state_array += $apply_state_temporary;

        });

        //检查商家是否报名该活动
        array_walk($dispose_data, function(&$item, $activity_id) use ($apply_state_array){
            $item['apply_sum'] = isset($apply_state_array[$activity_id]) ? (int)$apply_state_array[$activity_id] : 0;
        });

        return $dispose_data;
    }

    /**
     * 活动报名商品列表
     *
     * @param array $condition 查询条件
     * @param int $page 分页数
     * @return array 二维数组
     */
    public function getGoodsList($where, $limit = 0, $page = 0)
    {
        $marketing_activity_id = isset($where['marketing_activity_id']) ? (int)$where['marketing_activity_id'] : 0;
        //获取营销活动详情
        $map = array(
            'marketing_activity_id' => $marketing_activity_id
        );

        $marketing_activity_data = $this->table('marketing_activity')->field('marketing_activity_id,marketing_activity_type')->where($map)->find();
        //确定操作对象
        $marketing_activity_type = isset($marketing_activity_data['marketing_activity_type']) ? (int)$marketing_activity_data['marketing_activity_type'] : '';
        $model_name = $this->activityTypeShiftModel($marketing_activity_type);
        if (!$model_name) {
            return array();  //营销类型错误
        }

        $model_name = Model($model_name);
        $result = $model_name->getActivityGoodsList($where, $limit, $page);
        //将营销活动类型，加进数组中
        array_walk($result, function(&$item, $key) use ($marketing_activity_type) {
            $item['marketing_activity_type_int'] = $marketing_activity_type;
        });

        return $result;
    }

    /**
     * 活动报名商品列表
     *
     * @param int $marketing_activity_id 营销活动id
     * @param array $goods_list 需要处理的商品
     * @return array
     */
    public function disposeStoreGoodsSelect($marketing_activity_id = 0, $goods_list = array())
    {
        //获取营销活动详情
        $map = array(
            'marketing_activity_id' => (int)$marketing_activity_id
        );
        $marketing_activity_data = $this->table('marketing_activity')->field('marketing_activity_id,marketing_activity_type')->where($map)->find();
        //确定操作对象
        $model_name = $this->activityTypeShiftModel($marketing_activity_data['marketing_activity_type']);
        if (!$model_name) {
            return array();  //营销类型错误
        }

        $model_name = Model($model_name);
        $result = $model_name->disposeStoreGoodsSelect($marketing_activity_id, $goods_list);

        return $result;
    }

    /**
     * 添加活动
     *
     * @param array $input
     * @return bool
     */
    public function add($input)
    {
        $result = false;
        try {
            //打开事务
            $this->beginTransaction();
            //判断是否存在同一类型且时间交叉的数据
            $if_legal = $this->checkDataIfLegal($input);
            if ($if_legal !== true) {
                throw new Exception('相同时间内，存在同一定类型营销活动');
            }
            $marketing_activity_desc = isset($input['marketing_activity_desc']) ? $input['marketing_activity_desc'] : '';
            unset($input['marketing_activity_desc']);
            //添加活动记录
            $add_state = $this->table('marketing_activity')->insert($input);
            if (!$add_state) {
                throw new Exception('添加营销活动记录失败');
            }
            //添加活动扩展记录
            $extend_data = array(
                'marketing_activity_id' => $add_state,
                'marketing_activity_desc' => $marketing_activity_desc
            );
            $extend_state = $this->table('marketing_activity_extend')->insert($extend_data);
            if (!$extend_state) {
                throw new Exception('添加营销活动记录失败');
            }
            //提交事务
            $this->commit();
            $result = $add_state;
        }catch (Exception $e){
            //回滚事务
            $this->rollback();
            $this->setErrorInfo($e->getMessage());
        }
        return $result;
    }


    /**
     * 更新活动
     * @param  array   $input                 更新数据
     * @param  integer $marketing_activity_id 活动id
     * @param  boolean $if_alter              是否可以修改
     * @return bool
     */
    public function updates($input = array(), $marketing_activity_id = 0, $if_alter = false)
    {
        $result = false;
        try {
            $marketing_activity_id = (int)$marketing_activity_id;
            //打开事务
            $this->beginTransaction();
            //判断是否存在同一类型且时间交叉的数据
            $if_legal = $this->checkDataIfLegal($input, $marketing_activity_id);
            if ($if_legal !== true) {
                throw new Exception('相同时间内，存在同一定类型营销活动');
            }
            $marketing_activity_desc = isset($input['marketing_activity_desc']) ? $input['marketing_activity_desc'] : '';
            unset($input['marketing_activity_desc']);
            $map = array(
                'marketing_activity_id' => $marketing_activity_id
            );
            //若 if_alter 不为true，删除敏感的修改数据
            if ($if_alter !== true) {
                unset($input['marketing_activity_type']);
                unset($input['marketing_activity_style']);
                unset($input['marketing_activity_apply_start_date']);
                unset($input['marketing_activity_apply_end_date']);
                unset($input['marketing_activity_start_date']);
                unset($input['marketing_activity_end_date']);
                unset($input['store_goods_limit']);
            }

            //修改活动记录
            $alter_state = $this->table('marketing_activity')->where($map)->update($input);
            if (!$alter_state) {
                throw new Exception('修改营销活动记录失败');
            }
            //修改活动扩展记录
            $alter_state = $this->alterActivityExtend($marketing_activity_id, $marketing_activity_desc);
            if (!$alter_state) {
                throw new Exception($this->getErrorInfo());
            }
            //提交事务
            $this->commit();
            $result = true;
        }catch (Exception $e){
            //回滚事务
            $this->rollback();
            $this->setErrorInfo($e->getMessage());
        }
        return $result;
    }

    /**
     * 修改活动扩展数据
     * @param  int $marketing_activity_id   活动id
     * @param  string $marketing_activity_desc 扩展数据
     * @return  bool
     */
    public function alterActivityExtend($marketing_activity_id, $marketing_activity_desc)
    {
        $result = true;
        $marketing_activity_id = (int)$marketing_activity_id;
        //是否存在该扩展数据
        $map = array(
            'marketing_activity_id' => $marketing_activity_id
        );
        $if_exist = $this->table('marketing_activity_extend')->where($map)->find();
        if (empty($if_exist)) {  //没有数据，新增
            $extend_data = array(
                'marketing_activity_id' => $marketing_activity_id,
                'marketing_activity_desc' => $marketing_activity_desc
            );
            $extend_state = $this->table('marketing_activity_extend')->insert($extend_data);
            if (!$extend_state) {
                $this->setErrorInfo('修改活动扩展数据时，添加数据失败');
                $result = false;
            }
        } else {    //存在数据。修改
            $update_data = array(
                'marketing_activity_desc' => $marketing_activity_desc
            );
            $extend_state = $this->table('marketing_activity_extend')->where($map)->update($update_data);
            if (!$extend_state) {
                $this->setErrorInfo('修改活动扩展数据时失败');
                $result = false;
            }
        }
        return $result;
    }

    /**
     * 检查数据是否合法
     * @return true - 合法 / false - 不合法
     */
    private function checkDataIfLegal($check_data = array(), $exclude_id = 0)
    {
        $exclude_condition = empty($exclude_id) ? '' : ' AND marketing_activity_id != ' . (int)$exclude_id;
        //检查同类型数据是否交叉
        $marketing_activity_type = isset($check_data['marketing_activity_type']) ? (int)$check_data['marketing_activity_type'] : 1;
        $marketing_activity_start_date = isset($check_data['marketing_activity_start_date']) ? (int)$check_data['marketing_activity_start_date'] : 0;
        $marketing_activity_end_date = isset($check_data['marketing_activity_end_date']) ? (int)$check_data['marketing_activity_end_date'] : 0;
        //确保 $marketing_activity_start_date < $marketing_activity_end_date
        if ($marketing_activity_start_date > $marketing_activity_end_date) list($marketing_activity_start_date, $marketing_activity_end_date) = array($marketing_activity_end_date, $marketing_activity_start_date);

        $sql = "SELECT marketing_activity_id FROM shopnc_marketing_activity WHERE ((marketing_activity_start_date >= {$marketing_activity_start_date} AND marketing_activity_start_date <= {$marketing_activity_end_date}) OR (marketing_activity_end_date >= {$marketing_activity_start_date} AND marketing_activity_end_date <= {$marketing_activity_end_date}) OR (marketing_activity_start_date <= {$marketing_activity_start_date} AND marketing_activity_end_date >= {$marketing_activity_end_date}) OR (marketing_activity_start_date >= {$marketing_activity_start_date} AND marketing_activity_end_date <= {$marketing_activity_end_date})) AND marketing_activity_type = {$marketing_activity_type} AND marketing_activity_state = 1 {$exclude_condition} LIMIT 1";
        $if_exist = $this->query($sql);
        $if_exist = mysqli_fetch_array($if_exist,MYSQLI_ASSOC);
        return empty($if_exist);
    }

    /**
     * 删除营销活动
     *
     * @param array $id
     * @return bool
     */
    public function delMarketingActivity($ids = array())
    {
        $result = false;
        $ids = (array)$ids;
        if (empty($ids)) {
            $this->setErrorInfo('请选择操作对象');
            return $result;
        }
        //检查操作数据中是否存在不可删除的数据
        $allow_delete = $this->chechIfAllowDelte($ids);
        if ($allow_delete !== true) {
            return $result;
        }

        //删除相关数据
        try {
            //打开事务
            $this->beginTransaction();
            //删除营销活动
            $map = array(
                'marketing_activity_id' => array('in', $ids)
            );
            //获取删除的营销记录
            $delete_data = $this->table('marketing_activity')->field('marketing_activity_id,marketing_activity_type')->where($map)->select();
            //删除营销活动主记录
            $delete_state = $this->table('marketing_activity')->where($map)->delete();
            if (!$delete_state) {
                throw new Exception('删除营销活动记录失败');
            }
            //删除营销活动扩展
            $delete_extend = $this->table('marketing_activity_extend')->where($map)->delete();
            if (!$delete_extend) {
                throw new Exception('删除营销活动扩展记录失败');
            }
            //删除营销记录相关商品数据
            $del_goods_data = $this->disposeGoodsData($delete_data);   //将需要删除的数据，处理以营销类型分类的数组
            if (empty($del_goods_data)) {
                throw new Exception('数据处理失败');
            }
            $activity_type_map_relation = $this->activity_type_map_relation;  //营销类型对应表
            foreach ($del_goods_data as $marketing_activity_type => $item) {
                $model_name = isset($activity_type_map_relation[$marketing_activity_type]['table']) ? $activity_type_map_relation[$marketing_activity_type]['table'] : '';
                if (empty($model_name)) {
                    throw new Exception('错误的营销类型');
                }
                if( $model_name=='p_newbie_goods' || $model_name=='p_xianshi_all_goods' ){
                    $model_name = Model($model_name);
                    $delete_state = $model_name->deleteActivityGoods($item);
                    if (!$delete_state) {
                        throw new Exception($model_name->getErrorInfo());
                    }
                }

            }
            //提交事务
            $this->commit();
            $result = true;
        } catch (Exception $e) {
            //回滚事务
            $this->rollback();
            $this->setErrorInfo($e->getMessage());
        }

        return $result;
    }

    /**
     * 增加营销活动商品
     * @param array $add_data 增加数据
     */
    public function addMarketingActivityGoods($add_data = array())
    {
        $result = false;

        //获得营销活动数据
        $marketing_activity_id = isset($add_data['marketing_activity_id']) ? (int)$add_data['marketing_activity_id'] : 0;
        $field = 'marketing_activity_id,marketing_activity_type';
        $activity_data = $this->getActivityOpenDetails($marketing_activity_id, $field);
        if (empty($activity_data)) {
            $this->setErrorInfo('不存在该开启的活动');
            return $result;
        }

        //确定操作对象
        $model_name = $this->activityTypeShiftModel($activity_data['marketing_activity_type']);
        if (!$model_name) {
            $this->setErrorInfo('错误的营销类型');
            return $result;
        }
        $model_name = Model($model_name);
        //添加数据
        try {
            
            //打开事务
            $this->beginTransaction();
            $add_state = $model_name->addActivityGoodsData($add_data);
            if (!$add_state) {
                throw new Exception($model_name->getErrorInfo());
            }
            //提交事务
            $this->commit();
            $result = $add_state;
        } catch (Exception $e) {
            //回滚事务
            $this->rollback();
            $this->setErrorInfo($e->getMessage());
        }

        return $add_state;
    }

    /**
     * 获得活动状态为开启的活动的详情
     * @param  integer $marketing_activity_id 活动id
     * @return array
     */
    public function getActivityOpenDetails($marketing_activity_id = 0, $field = '*')
    {
        $map = array(
            'marketing_activity_id' => $marketing_activity_id,
            'marketing_activity_state' => self::ACTIVITY_OPEN
        );
        return $this->table('marketing_activity')->field($field)->where($map)->find();
    }

    /**
     * 检查是否允许修改
     * @param  integer $marketing_activity_id 活动id
     * @return bool true - 允许 / false - 不允许
     */
    public function chechIfAllowAlter($marketing_activity_id = 0)
    {
        $result = false;
        //获取活动信息
        $map = array(
            'marketing_activity_id' => array('eq', (int)$marketing_activity_id),
            // 'marketing_activity_start_date' => array('lt', TIMESTAMP),
            // 'marketing_activity_end_date' => array('gt', TIMESTAMP),
            // 'marketing_activity_state' => array('eq', 1)
        );
        $activity_data = $this->table('marketing_activity')->field('marketing_activity_id,marketing_activity_type,marketing_activity_start_date,marketing_activity_end_date,marketing_activity_state')->where($map)->find();
        if (empty($activity_data)) {
            $this->setErrorInfo('不存在该活动');
            return $result;
        }
        //活动是否是开启状态且以开始
        if(($activity_data['marketing_activity_state'] == self::ACTIVITY_OPEN) && ($activity_data['marketing_activity_start_date'] < TIMESTAMP) && ($activity_data['marketing_activity_end_date'] > TIMESTAMP)) {
            $this->setErrorInfo('该活动状态为开启，且活动已开始，不允许修改');
            return $result;
        }

        //是否存在已报名商品
        $model_name = $this->activityTypeShiftModel($activity_data['marketing_activity_type']);
        if (!$model_name) {
            $this->setErrorInfo('错误的营销类型');
            return $result;
        }
        $model_name = Model($model_name);/*砍价:p_kanjia_goods;拼团:p_pintuan_goods;新人专享:p_newbie_goods;限时特惠:p_xianshi_all_goods*/
        $apply_data = $model_name->ifExistApplyGoods((int)$marketing_activity_id);

        return !$apply_data;
    }

    /**
     * 活动类型转换为模型名称
     * @return string / false
     */
    public function activityTypeShiftModel($marketing_activity_type)
    {
        $activity_type_map_relation = $this->activity_type_map_relation;  //营销类型对应表
        $model_name = isset($activity_type_map_relation[$marketing_activity_type]['table']) ? $activity_type_map_relation[$marketing_activity_type]['table'] : '';
        return $model_name ? $model_name : false;
    }


    /**
     * 将数据处理为以营销类型分类的数组
     * @param  array  $dispose_data 要处理的数据
     * @return array
     */
    public function disposeGoodsData($dispose_data = array())
    {
        $result = array();
        foreach ($dispose_data as $item) {
            $marketing_activity_type = isset($item['marketing_activity_type']) ? (int)$item['marketing_activity_type'] : 0;
            $marketing_activity_id = isset($item['marketing_activity_id']) ? (int)$item['marketing_activity_id'] : 0;
            if ($marketing_activity_type) $result[$marketing_activity_type][] = $marketing_activity_id;
        }
        return $result;
    }

    /**
     * 检查是否允许删除
     * @param  array  $ids 需要检查的id
     * @return bool   true-允许操作/false-不允许
     */
    public function chechIfAllowDelte($ids = array())
    {
        $ids = (array)$ids;
        if (empty($ids)) {
            $this->setErrorInfo('请选择校验的对象');
            return false;
        }

        $map = array(
            'marketing_activity_id' => array('in', $ids),
        );

        $activity_lists = $this->table('marketing_activity')->field('marketing_activity_id,marketing_activity_title,marketing_activity_type,marketing_activity_start_date,marketing_activity_end_date,marketing_activity_state')->where($map)->select();
        if (empty($activity_lists)) {
            $this->setErrorInfo('不存在校验的数据');
            return false;
        }

        /*检查操作数据下属是否存在数据 begin*/
        $dispose_data = array();  //存放按营销类型分组的数据
        foreach ($activity_lists as $item) {
            //检查是否存在数据
            $model_name = $this->activityTypeShiftModel($item['marketing_activity_type']);
            if (!$model_name) continue;
            $model_name = Model($model_name);
            $if_exist = true; //默认存在
            if (method_exists($model_name, 'ifExistGoods')) {
                $if_exist = $model_name->ifExistGoods((int)$item['marketing_activity_id']);
            }
            if ($if_exist === true) $dispose_data[] = $item;   //如果不存在商品，不用进行下一步校验
        }
        if (empty($dispose_data)) return true;  //校验通过对数据，直接返回成功
        /*检查操作数据下属是否存在数据 end*/

        //只有关闭且过期的活动，能删除
        $error_info = array();  //错误信息
        array_walk($dispose_data, function($item, $keys)use(&$error_info) {
            //活动状态不为关闭
            // if (!isset($item['marketing_activity_state']) || ($item['marketing_activity_state'] != self::ACTIVITY_CLOSE)) {
            //     $error_info[] = 'ID为['.$item["marketing_activity_id"].'],标题为['.$item['marketing_activity_title'].'],的营销活动，活动状态为开启，不允许删除！';
            // }
            //活动还未过期
            if (!isset($item['marketing_activity_end_date']) || ($item['marketing_activity_end_date'] > TIMESTAMP)) {
                $error_info[] = 'ID为['.$item["marketing_activity_id"].'],标题为['.$item['marketing_activity_title'].'],的营销活动，活动还未过期，不允许删除！';
            }
        });
        if (!empty($error_info)){
            $this->setErrorInfo(implode($error_info, '|'));
            return false;
        }
        return true;
    }

    /**
     * 根据id查询一条活动
     *
     * @param int $marketing_activity_id 活动id
     * @return array 一维数组
     */
    public function getOneById($marketing_activity_id)
    {
        $field = 'min_num,marketing_activity.marketing_activity_id,marketing_activity.marketing_activity_title,marketing_activity.marketing_activity_type,marketing_activity.marketing_activity_banner,marketing_activity.marketing_activity_style,marketing_activity.marketing_activity_apply_start_date,marketing_activity.marketing_activity_apply_end_date,marketing_activity.marketing_activity_start_date,marketing_activity.marketing_activity_end_date,marketing_activity.store_goods_limit,marketing_activity.marketing_activity_sort,marketing_activity.marketing_activity_state,marketing_activity.marketing_activity_show,marketing_activity_extend.marketing_activity_desc';
        $map['marketing_activity.marketing_activity_id'] = (int)$marketing_activity_id;
        $result = $this->table('marketing_activity,marketing_activity_extend')
                    ->field($field)
                    ->join('left')
                    ->on('marketing_activity.marketing_activity_id = marketing_activity_extend.marketing_activity_id')
                    ->where($map)
                    ->find();
        if (!empty($result)) {
            //活动说明
            $result['marketing_activity_desc_html'] =  isset($result['marketing_activity_desc']) ? $result['marketing_activity_desc'] : '';
            $result['marketing_activity_desc'] =  isset($result['marketing_activity_desc']) ? msubstr(strip_tags(html_entity_decode($result['marketing_activity_desc'])), 0, 60) : '';

            //横幅地址
            $result['marketing_activity_banner_all'] = (isset($result['marketing_activity_banner']) && !empty($result['marketing_activity_banner'])) ? UPLOAD_SITE_URL.DS.ATTACH_ACTIVITY.DS.$result['marketing_activity_banner'] : '';
        }
        return $result;
    }

    /**
     * 获取单条数据
     * @param  array  $condition 过滤条件
     * @return array
     */
    public function getOneData($condition = array())
    {
        $field = 'marketing_activity.marketing_activity_id,marketing_activity.marketing_activity_title,marketing_activity.marketing_activity_type,marketing_activity.marketing_activity_banner,marketing_activity.marketing_activity_style,marketing_activity.marketing_activity_apply_start_date,marketing_activity.marketing_activity_apply_end_date,marketing_activity.marketing_activity_start_date,marketing_activity.marketing_activity_end_date,marketing_activity.store_goods_limit,marketing_activity.marketing_activity_sort,marketing_activity.marketing_activity_state,marketing_activity.marketing_activity_show,marketing_activity_extend.marketing_activity_desc';
        $result = $this->table('marketing_activity,marketing_activity_extend')
                    ->field($field)
                    ->join('left')
                    ->on('marketing_activity.marketing_activity_id = marketing_activity_extend.marketing_activity_id')
                    ->where($condition)
                    ->find();
        if (!empty($result)) {
            //活动说明
            $result['marketing_activity_desc_html'] =  isset($result['marketing_activity_desc']) ? $result['marketing_activity_desc'] : '';
            $result['marketing_activity_desc'] =  isset($result['marketing_activity_desc']) ? msubstr(strip_tags(html_entity_decode($result['marketing_activity_desc'])), 0, 60) : '';

            //横幅地址
            $result['marketing_activity_banner_all'] = (isset($result['marketing_activity_banner']) && !empty($result['marketing_activity_banner'])) ? UPLOAD_SITE_URL.DS.ATTACH_ACTIVITY.DS.$result['marketing_activity_banner'] : '';
        }
        return $result;
    }

    /**
     * 构造查询条件
     *
     * @param array $condition 条件数组
     * @return string
     */
    private function getCondition($condition){
        $conditionStr   = '1';
        if($condition['marketing_activity_id'] != ''){
            $conditionStr .= " and marketing_activity.marketing_activity_id = '{$condition['marketing_activity_id']}' ";
        }
        if($condition['marketing_activity_type'] != ''){
            $conditionStr   .= " and marketing_activity.marketing_activity_type = '{$condition['marketing_activity_type']}' ";
        }
        if ((string)$condition['marketing_activity_state'] !== ''){
            $conditionStr   .= " and marketing_activity.marketing_activity_state = '{$condition['marketing_activity_state']}' ";
        }
        //活动删除in
        if(isset($condition['marketing_activity_id_in'])){
            if ($condition['marketing_activity_id_in'] == ''){
                $conditionStr   .= " and marketing_activity_id in('')";
            }else{
                $conditionStr   .= " and marketing_activity_id in({$condition['marketing_activity_id_in']}) ";
            }
        }
        if($condition['marketing_activity_title'] != ''){
            $conditionStr   .= " and marketing_activity.marketing_activity_title like '%{$condition['marketing_activity_title']}%' ";
        }
        //当前时间大于结束时间（过期）
        if ($condition['marketing_activity_enddate_greater'] != ''){
            $conditionStr   .= " and marketing_activity.marketing_activity_end_date < '{$condition['marketing_activity_enddate_greater']}'";
        }
        //可删除的活动记录
        if ($condition['marketing_activity_enddate_greater_or'] != ''){
            $conditionStr   .= " or marketing_activity.marketing_activity_end_date < '{$condition['marketing_activity_enddate_greater_or']}'";
        }
        //某时间段内正在进行的活动
        if($condition['marketing_activity_daterange'] != ''){
            $conditionStr .= " and (marketing_activity.marketing_activity_end_date >= '{$condition['marketing_activity_daterange']['startdate']}' and marketing_activity.marketing_activity_start_date <= '{$condition['marketing_activity_daterange']['enddate']}')";
        }
        if($condition['opening']){//在有效期内、活动状态为开启
            $conditionStr   .= " and (marketing_activity.marketing_activity_start_date <= " . TIMESTAMP . " and marketing_activity.marketing_activity_end_date >= " . TIMESTAMP . " and marketing_activity.marketing_activity_state =1)";
        }
        if($condition['store_marketing_activity']){//在有效期内、活动状态为开启、活动显示状态为显示
            $conditionStr   .= " AND (marketing_activity.marketing_activity_end_date >= " . TIMESTAMP . " AND marketing_activity.marketing_activity_state = 1 AND marketing_activity.marketing_activity_show = 1)";
        }

        // 时间段检索
        if ($condition['pdates']) {
            $conditionStr .= " and ({$condition['pdates']})";
        }

        return $conditionStr;
    }


    /**
     * 修改活动商品数据
     * @param  array  $marketing_activity_id        活动编号
     * @param  array  $ids        商品id
     * @param  array  $alter_data 修改数据
     * @return bool
     */
    public function updatesGoodsData($marketing_activity_id = 0, $ids = array(), $alter_data = array())
    {
        $result = false;
        $ids = (array)$ids;
        if (empty($ids)) {
            $this->setErrorInfo('请选择操作对象');
            return $result;
        }
        //根据marketing_activity_id，找出对应模型
        $map = array(
            'marketing_activity_id' => (int)$marketing_activity_id
        );

        $marketing_activity_data = $this->table('marketing_activity')->field('marketing_activity_id,marketing_activity_type')->where($map)->find();
        //确定操作对象
        $model_name = $this->activityTypeShiftModel($marketing_activity_data['marketing_activity_type']);

        if (!$model_name) {
            $this->setErrorInfo('营销类型错误');
            return $result;
        }
        $model_name = Model($model_name);
        try {
            //打开事务
            $this->beginTransaction();
            $alter_state = $model_name->updateActivityGoods($marketing_activity_id, $ids, $alter_data);
            if (!$alter_state) {
                throw new Exception($model_name->getErrorInfo());
            }
            //提交事务
            $this->commit();
            $result = $alter_state;
        } catch (Exception $e) {
            //回滚事务
            $this->rollback();
            $this->setErrorInfo($e->getMessage());
        }

        return $result;
    }

    /**
     * 迁移活动商品数据
     * @param  integer $original_activity_id  原来营销活动id
     * @param  integer $receive_activity_id   接收营销活动id
     * @param  array   $ids                   迁移的数据
     * @param  array   $user_data             用户数据
     * @return bool
     */
    public function migrateActivityGoodsData($original_activity_id = 0, $receive_activity_id = 0, $ids = array(), $user_data = array())
    {
        $result = false;
        $original_activity_id = (int)$original_activity_id;
        $receive_activity_id  = (int)$receive_activity_id;
        $ids                  = (array)$ids;
        if (empty($ids)) {
            $this->setErrorInfo('请选择操作对象');
            return $result;
        }
        //判断迁移前后营销活动是否变化
        if ($original_activity_id === $receive_activity_id) {
            $this->setErrorInfo('迁移前后的营销活动没有变化');
            return $result;
        }

        //找到原来营销活动的模型
        $map = array(
            'marketing_activity_id' => $original_activity_id
        );
        $original_activity_data = $this->table('marketing_activity')->field('marketing_activity_id,marketing_activity_type')->where($map)->find();
        $original_model = $this->activityTypeShiftModel($original_activity_data['marketing_activity_type']);
        if (!$original_model) {
            $this->setErrorInfo('原来的营销活动找不到对应的模型');
            return $result;
        }
        $original_model = Model($original_model);

        //找到接受营销活动的模型
        $map = array(
            'marketing_activity_id' => $receive_activity_id
        );
        $receive_activity_data = $this->table('marketing_activity')->field('marketing_activity_id,marketing_activity_type')->where($map)->find();
        $receive_model = $this->activityTypeShiftModel($receive_activity_data['marketing_activity_type']);
        if (!$receive_model) {
            $this->setErrorInfo('接收的营销活动找不到对应的模型');
            return $result;
        }
        $receive_model = Model($receive_model);

        try {
            //打开事务
            $this->beginTransaction();
            //获取迁移的所有数据  -- 返回 goods_id,newbie_price AS promotion_price,upper_limit
            $receive_data = $original_model->getActivityGoodsListId($ids);
            $receive_data = array_under_reset($receive_data, 'activity_goods_id');
            if (empty($receive_data)) {
                throw new Exception('获取迁移数据出错');
            }
            //删除原先所有数据
            $delete_ids = array_keys($receive_data);
            $name_change_state = $original_model->getNameChangeState();
            $check_state = isset($name_change_state['soft_delete']) ? (int)$name_change_state['soft_delete'] : '';
            if ($check_state === '') {
                throw new Exception('模型中的常量设置错误');
            }
            $delete_data = array(
                'check_state' => $check_state
            );
            $delete_state = $original_model->updateActivityGoods($original_activity_id, $delete_ids, $delete_data);
            if (!$delete_state) {
                throw new Exception($original_model->getErrorInfo());
            }
            //添加接收新数据 -- 新增数据必要的列 marketing_activity_id,goods_id,promotion_price,upper_limit,admin_apply,apply_user_id,apply_user_name
            foreach ($receive_data as $item) {
                $add_data = array(
                    'marketing_activity_id' => $receive_activity_id,
                    'goods_id'              => $item['goods_id'],
                    'promotion_price'       => $item['promotion_price'],
                    'upper_limit'           => $item['upper_limit'],
                    'admin_apply'           => $user_data['admin_apply'],
                    'apply_user_id'         => $user_data['apply_user_id'],
                    'apply_user_name'       => $user_data['apply_user_name'],
                );
                $add_state = $receive_model->addActivityGoodsData($add_data);
                if (!$add_state) {
                    throw new Exception($receive_model->getErrorInfo());
                }
            }
            //提交事务
            $this->commit();
            $result = true;
        } catch (Exception $e) {
            //回滚事务
            $this->rollback();
            $this->setErrorInfo($e->getMessage());
        }

        return $result;
    }

}
